package org.n.shop.listener;

import lombok.AllArgsConstructor;
import org.n.shop.domain.entity.OrderDetail;
import org.n.shop.mapper.OrderDetailMapper;
import org.n.shop.mapper.ShoppingCartMapper;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static org.n.shop.config.RedisConfig.PREFIX_ORDER;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String key = message.toString();
        if (key.indexOf(PREFIX_ORDER) != -1) {
            String[] data = key.substring(PREFIX_ORDER.length()).split("\\|");
            int orderId = Integer.parseInt(data[0]);
            int[] ids = stringToIntArray(data[1]);

            orderDetailMapper.updateLogisticsType(orderId, 6);
            shoppingCartMapper.updateIds(ids);
        }
    }

    private int[] stringToIntArray(String str) {
        String[] data = str.split(",");
        int[] ids = new int[data.length];

        for (int i = 0; i < data.length; i++) {
            ids[i]= Integer.parseInt(data[i]);
        }

        return ids;
    }
}